package com.zhuqi.redis.set;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author : ZhuQi
 * @version : 时间:2022/1/10 11:50 版本:
 * 测试 Redis Set 集合
 *
 */
@Component
@Slf4j
public class SetRedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 测试内容:
     */
    public void test() throws Exception {
        SetOperations<String, String> stringStringSetOperations = stringRedisTemplate.opsForSet();

        // 向set集合添加元素
        stringStringSetOperations.add("zhuqi", "唱", "跳", "看B站");
        stringStringSetOperations.add("wang", "唱", "跳", "看抖音");

        // 取两个key的差集 有主次关系，以第一个key后面key做比较。输出第一个key的差集。
        Set<String> differenceSet = stringStringSetOperations.difference("zhuqi", "wang");
        Set<String> differenceSet2 = stringStringSetOperations.difference("wang", "zhuqi");
        log.info("两个集合取差集{}", differenceSet);
        log.info("两个集合取差集{}", differenceSet2);

        // 取两个key的交集，无主次关系。
        Set<String> intersectSet = stringStringSetOperations.intersect("zhuqi", "wang");
        log.info("两个集合取交集{}", intersectSet);

        // 取两个key的并集
        Set<String> union = stringStringSetOperations.union("zhuqi", "wang");
        log.info("两个集合取并集{}", union);

        // 检查该KEY中
        Boolean member = stringStringSetOperations.isMember("zhuqi", "唱");
        log.info("检查key是否保护某个值:{}", member ? "存在" : "不存在");

        // 检查某个set集合中元素个数
        Long zhuqi = stringStringSetOperations.size("zhuqi");
        log.info("该set集合大小为:{}", zhuqi);

        // 将某个key中的某个值移动到另一个key下面
        stringStringSetOperations.move("zhuqi",  "看B站", "wang");

        // 从集合中弹出一个值，并删除
        String zhuqi1 = stringStringSetOperations.pop("zhuqi");
        log.info("从集合中弹出一个值:{}", zhuqi1);
    }

    /**
     * 测试内容: 测试复杂命令
     */
    public void test2() throws Exception {
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();
        setOperations.add("zhuqi", "唱", "跳", "看B站");
        setOperations.add("wang", "唱", "跳", "看抖音");

        HashSet<String> strings = new HashSet<>();
        strings.add("唱");
        strings.add("看美女");
        // 根据集合取差集值，并将数据存在指定集合,参数1 需要比较的key 参数2 被比较的key 参数3 存储的目标key
        setOperations.differenceAndStore("wang", "zhuqi", "zhuqi1");

        // 根据集合取交集值，并将数据存在指定集合,参数1 需要比较的key 参数2 被比较的key 参数3 存储的目标key
        setOperations.intersectAndStore("wang", "zhuqi", "zhuqi2");

        // 根据集合取并集值，并将数据存在指定集合,参数1 需要比较的key 参数2 被比较的key 参数3 存储的目标key
        setOperations.unionAndStore("wang", "zhuqi", "zhuqi2");
    }
}
